import 'package:flutter/material.dart';
import '../services/file_service.dart';
import '../services/theme_service.dart';

class FileListView extends StatelessWidget {
  final List<Map<String, dynamic>> files;
  final bool isLoading;
  final bool isSelectMode;
  final Set<int> selectedFileIds;
  final Function(int) onFileSelected;
  final Function(int, String, String) onFileTap;
  final Widget? emptyWidget;
  final ScrollController? scrollController;
  final Future<void> Function()? onRefresh;
  final bool showAlternateBackground;

  const FileListView({
    super.key,
    required this.files,
    required this.isLoading,
    required this.isSelectMode,
    required this.selectedFileIds,
    required this.onFileSelected,
    required this.onFileTap,
    this.emptyWidget,
    this.scrollController,
    this.onRefresh,
    this.showAlternateBackground = true,
  });

  // 获取文件类型对应的图标
  IconData _getIconForFile(Map<String, dynamic> file) {
    // 处理目录
    if (file['is_directory'] == true) {
      return Icons.folder;
    }

    final fileName = (file['file_name'] ?? '').toLowerCase();
    if (fileName.isEmpty) {
      return Icons.insert_drive_file;
    }
    if (fileName.endsWith('.jpg') ||
        fileName.endsWith('.jpeg') ||
        fileName.endsWith('.png') ||
        fileName.endsWith('.gif') ||
        fileName.endsWith('.bmp') ||
        fileName.endsWith('.webp') ||
        fileName.endsWith('.heic')) {
      return Icons.image;
    } else if (fileName.endsWith('.mp4') ||
        fileName.endsWith('.avi') ||
        fileName.endsWith('.mov') ||
        fileName.endsWith('.wmv') ||
        fileName.endsWith('.flv') ||
        fileName.endsWith('.mkv') ||
        fileName.endsWith('.webm')) {
      return Icons.video_file;
    } else if (fileName.endsWith('.mp3') ||
        fileName.endsWith('.wav') ||
        fileName.endsWith('.ogg') ||
        fileName.endsWith('.m4a') ||
        fileName.endsWith('.flac') ||
        fileName.endsWith('.aac')) {
      return Icons.audio_file;
    } else if (fileName.endsWith('.pdf') ||
        fileName.endsWith('.doc') ||
        fileName.endsWith('.docx') ||
        fileName.endsWith('.xls') ||
        fileName.endsWith('.xlsx') ||
        fileName.endsWith('.ppt') ||
        fileName.endsWith('.pptx') ||
        fileName.endsWith('.txt') ||
        fileName.endsWith('.json') ||
        fileName.endsWith('.xml') ||
        fileName.endsWith('.csv')) {
      return Icons.description;
    } else {
      return Icons.insert_drive_file;
    }
  }

  // 获取文件类型对应的颜色
  Color _getColorForFile(Map<String, dynamic> file, ThemeData theme) {
    // 处理目录
    if (file['is_directory'] == true) {
      return Colors.amber;
    }

    final fileName = (file['file_name'] ?? '').toLowerCase();
    if (fileName.isEmpty) {
      return Colors.grey;
    }
    if (fileName.endsWith('.jpg') ||
        fileName.endsWith('.jpeg') ||
        fileName.endsWith('.png') ||
        fileName.endsWith('.gif') ||
        fileName.endsWith('.bmp') ||
        fileName.endsWith('.webp') ||
        fileName.endsWith('.heic')) {
      return theme.primaryColor;
    } else if (fileName.endsWith('.mp4') ||
        fileName.endsWith('.avi') ||
        fileName.endsWith('.mov') ||
        fileName.endsWith('.wmv') ||
        fileName.endsWith('.flv') ||
        fileName.endsWith('.mkv') ||
        fileName.endsWith('.webm')) {
      return Colors.pinkAccent;
    } else if (fileName.endsWith('.mp3') ||
        fileName.endsWith('.wav') ||
        fileName.endsWith('.ogg') ||
        fileName.endsWith('.m4a') ||
        fileName.endsWith('.flac') ||
        fileName.endsWith('.aac')) {
      return Colors.purpleAccent;
    } else if (fileName.endsWith('.pdf') ||
        fileName.endsWith('.doc') ||
        fileName.endsWith('.docx') ||
        fileName.endsWith('.xls') ||
        fileName.endsWith('.xlsx') ||
        fileName.endsWith('.ppt') ||
        fileName.endsWith('.pptx') ||
        fileName.endsWith('.txt') ||
        fileName.endsWith('.json') ||
        fileName.endsWith('.xml') ||
        fileName.endsWith('.csv')) {
      return Colors.deepPurpleAccent;
    } else {
      return Colors.teal;
    }
  }

  String _formatDateTime(String dateStr) {
    try {
      final date = DateTime.parse(dateStr);
      final now = DateTime.now();
      final difference = now.difference(date);

      // 如果是今天的文件
      if (date.year == now.year &&
          date.month == now.month &&
          date.day == now.day) {
        return '今天 ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
      }
      // 如果是昨天的文件
      else if (difference.inDays == 1) {
        return '昨天 ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
      }
      // 如果是今年的文件
      else if (date.year == now.year) {
        return '${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
      }
      // 其他情况
      return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
    } catch (e) {
      return '未知时间';
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    if (files.isEmpty && !isLoading) {
      return emptyWidget ?? const SizedBox.shrink();
    }

    Widget listView = ListView.builder(
      controller: scrollController,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      itemCount: files.length + (isLoading ? 1 : 0),
      itemBuilder: (context, index) {
        if (index == files.length) {
          return Center(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(theme.primaryColor),
              ),
            ),
          );
        }

        final file = files[index];
        final fileId = file['id'] as int;
        final fileName = file['file_name'] as String? ?? '未知文件名';
        final fileType = file['file_type'] as String? ?? '未知类型';
        final fileSize = FileService.formatFileSize(file['file_size'] ?? 0);
        final uploadTime = _formatDateTime(file['upload_time'] ?? '');
        final isSelected = selectedFileIds.contains(fileId);

        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 4),
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              onTap: () {
                if (isSelectMode) {
                  onFileSelected(fileId);
                } else {
                  onFileTap(fileId, fileName, fileType);
                }
              },
              onLongPress: () {
                if (!isSelectMode) {
                  onFileSelected(fileId);
                }
              },
              child: Container(
                decoration: BoxDecoration(
                  color:
                      isSelected
                          ? theme.primaryColor.withOpacity(0.1)
                          : (showAlternateBackground && index % 2 == 0
                              ? Colors.white
                              : theme.primaryColor.withOpacity(0.05)),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                    color:
                        isSelected
                            ? theme.primaryColor
                            : Colors.grey.withOpacity(0.1),
                    width: 1,
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(8),
                  child: Row(
                    children: [
                      // 文件类型图标
                      Container(
                        width: 32,
                        height: 32,
                        decoration: BoxDecoration(
                          color: _getColorForFile(file, theme).withOpacity(0.1),
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: Icon(
                          _getIconForFile(file),
                          color: _getColorForFile(file, theme),
                          size: 16,
                        ),
                      ),
                      const SizedBox(width: 8),
                      // 文件信息
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              fileName,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: AppStyleHelper.getFileCountStyle(context),
                            ),
                            const SizedBox(height: 1),
                            Text(
                              file['is_directory'] == true
                                  ? _formatDateTime(file['upload_time'] ?? '')
                                  : '${FileService.formatFileSize(file['file_size'] ?? 0)} · ${_formatDateTime(file['upload_time'] ?? '')}',
                              style: AppStyleHelper.getFileInfoStyle(context),
                            ),
                          ],
                        ),
                      ),
                      // 选择状态
                      InkWell(
                        onTap: () {
                          onFileSelected(fileId);
                        },
                        child: Container(
                          width: 12,
                          height: 12,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color:
                                isSelected
                                    ? theme.primaryColor
                                    : Colors.grey.withOpacity(0.1),
                            border: Border.all(
                              color:
                                  isSelected
                                      ? theme.primaryColor
                                      : Colors.grey.withOpacity(0.3),
                              width: 1,
                            ),
                          ),
                          child:
                              isSelected
                                  ? const Icon(
                                    Icons.check,
                                    color: Colors.white,
                                    size: 8,
                                  )
                                  : null,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );

    if (onRefresh != null) {
      listView = RefreshIndicator(
        color: theme.primaryColor,
        onRefresh: onRefresh!,
        child: listView,
      );
    }

    return listView;
  }
}
